package com.cmse.service.impl;

import java.util.List;

import com.cmse.persistence.dao.IUserDao;
import com.cmse.persistence.domain.User;
import com.cmse.persistence.enmu.FetchOrderType;
import com.cmse.persistence.enmu.RoleType;
import com.cmse.service.IUserService;
import com.cmse.util.EncryptionUtil;

/**
 * @author wulibin, exceptsky@gmail.com, 2012-3-15 下午2:30:43
 * 
 */
public class UserService  extends BaseService<User> implements IUserService{
	private IUserDao userDao;
	
	@Override
	public void add(User user) {
		String PwMd5 = EncryptionUtil.encodeMD5(user.getPassword());
		user.setPassword(PwMd5);
		dao.add(user);
	}
	
	@Override
	public User getByName(String name) {
		return userDao.getByName(name);
	}

	@Override
	public String getSecurityAnswer(long uid) {
		return get(uid).getSecurityAnswer();
	}

	@Override
	public String getSecurityQuestion(long uid) {
		return get(uid).getSecurityQuestion();
	}

	@Override
	public boolean login(String name, String pw) {
		User user = getByName(name);
		if(null != user){
			String PwMd5 = EncryptionUtil.encodeMD5(pw);
			if(PwMd5.equals(user.getPassword())){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	@Override
	public boolean register(User user) {
		String name = user.getName();
		if(null == getByName(name)){
			add(user);
			return true;
		}else{
			return false;
		}
	}

	@Override
	public long getCountByRole(RoleType role) {
		User userExp = new User();
		userExp.setRole(role.getName());
		return userDao.getCountByCondition(userExp);
	}
	

	@Override
	public List<User> getUsersByRole(RoleType role, int page){
		User userExp = new User();
		userExp.setRole(role.getName());
		return userDao.getByCondition(userExp, pageLength*page, pageLength, FetchOrderType.CREATE_DESC);
	}

	@Override
	public List<User> searchByName(String key, int page){
		return userDao.search(pageLength*page, pageLength, key);
		
	}
	@Override
	public long countOfSearch(String key){
		return userDao.countOfsearch(key);
	}
	
	@Override
	public User updatePassword(User user, String oldPw, String newPw){
		String oldPwMd5 = EncryptionUtil.encodeMD5(oldPw);
		String newPwMd5 = EncryptionUtil.encodeMD5(newPw);
		if(user.getPassword().equals(oldPwMd5)){
			user.setPassword(newPwMd5);
			userDao.update(user);
			return user;
		}else{
			return null;
		}
	}
	
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
		setDao(userDao);
	}
}
